package service

import (
	"errors"

	"gitee.com/cyanbleeze/go-image-management/internal/model"
	"gitee.com/cyanbleeze/go-image-management/pkg/app"
)

type PictureRequest struct {
	ID uint `json:"id" binding:"required,min=1"`
}

type PictureListRequest struct {
	CategoryID uint `form:"category_id" json:"category_id" binding:"required,min=1"`
}

type CreatePictureRequest struct {
	CategoryID uint   `json:"category_id" binding:"required,min=1"`
	Title      string `json:"title" binding:"required,min=2,max=30"`
	Desc       string `json:"desc" binding:"max=255"`
	ImageUrl   string `json:"image_url" binding:"url"`
}

type UpdatePictureRequest struct {
	ID         uint   `json:"id,omitempty" binding:"required,min=1"`
	CategoryID uint   `json:"category_id,omitempty" binding:"required,min=1"`
	Title      string `json:"title,omitempty" binding:"required,min=2,max=30"`
	Desc       string `json:"desc,omitempty" binding:"omitempty,min=4,max=255"`
	ImageUrl   string `json:"image_url,omitempty" binding:"omitempty,url"`
}

type DeletePictureRequest struct {
	ID uint `json:"id" binding:"required,min=1"`
}

func (svc *Service) CreatePicture(params *CreatePictureRequest) error {
	userID, exist := svc.ctx.Get("userID")
	if !exist {
		return errors.New("登录用户信息不存在")
	}
	return svc.dao.CreatePicture(
		params.Title,
		params.ImageUrl,
		params.Desc,
		userID.(uint),
		params.CategoryID,
	)
}

func (svc *Service) UpdatePicture(params *UpdatePictureRequest) error {
	userID, exist := svc.ctx.Get("userID")
	if !exist {
		return errors.New("登录用户信息不存在")
	}
	_, err := svc.dao.GetPictureByUID(
		params.ID,
		userID.(uint),
	)
	if err != nil {
		return errors.New("图片不存在")
	}
	return svc.dao.UpdatePicture(
		params.ID,
		params.Title,
		params.ImageUrl,
		params.Desc,
		params.CategoryID,
	)
}

func (svc *Service) DeletePicture(params *DeletePictureRequest) error {
	userID, exist := svc.ctx.Get("userID")
	if !exist {
		return errors.New("登录用户信息不存在")
	}
	_, err := svc.dao.GetPictureByUID(
		params.ID,
		userID.(uint),
	)
	if err != nil {
		return errors.New("图片不存在")
	}
	return svc.dao.DeletePicture(
		params.ID,
		userID.(uint),
	)
}

func (svc *Service) GetPicture(params *PictureRequest) (*model.Picture, error) {
	userID, exist := svc.ctx.Get("userID")
	if !exist {
		return nil, errors.New("登录用户信息不存在")
	}
	d, err := svc.dao.GetPictureByUID(params.ID, userID.(uint))
	return &d, err
}

func (svc *Service) GetPictureList(params *PictureListRequest, pager *app.Pager) ([]*model.Picture, int, error) {
	userID, exist := svc.ctx.Get("userID")
	if !exist {
		return nil, 0, errors.New("登录用户信息不存在")
	}
	detailCount, err := svc.dao.CountPictureListByCategoryID(userID.(uint), params.CategoryID)
	if err != nil {
		return nil, 0, err
	}
	detailList, err := svc.dao.GetPictureList(params.CategoryID, userID.(uint), pager.Page, pager.PageSize)
	if err != nil {
		return nil, 0, err
	}
	return detailList, detailCount, nil
}
